package dictdatalogic

import (
	"context"

	"go-zero-admin/apps/system/cmd/rpc/internal/svc"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/apps/system/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddDictDataLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddDictDataLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddDictDataLogic {
	return &AddDictDataLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddDictDataLogic) AddDictData(in *syspb.AddDictDataReq) (*syspb.AddDictDataResp, error) {
	dictData := in.GetParams()
	if dictData == nil || dictData.GetDictLabel() == "" || dictData.GetDictValue() == "" ||
		dictData.GetDictType() == "" || dictData.GetCreateUser() == "" || dictData.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("新增字典数据失败：参数缺失"),
			tool.GetErrMsgFormat("insert dictData"), "params is not existed", in)
	}

	// 数据转换
	var data model.SysDictData
	_ = copier.Copy(&data, dictData)

	// 保存数据
	_, err := l.svcCtx.SysDictDataModel.InsertEx(l.ctx, nil, []*model.SysDictData{&data})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DbError),
			tool.GetErrMsgFormat("insert dictData"), err, in)
	}
	return &syspb.AddDictDataResp{}, nil
}
